package com.leetcode.support;

import java.util.ArrayList;

public class TreeNode {

    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode() {

    }

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    /**
     * 把一个只包含int和null的数组转为TreeNode对象
     * 重点是不断的刷新父节点集合和子节点集合
     */
    public TreeNode(Object[] data) {
        this.val = (int) data[0];
        // 父节点集合
        ArrayList<TreeNode> parentNodes = new ArrayList<>();
        parentNodes.add(this);
        int index = 0; // 当前父节点的下标
        // 子节点集合
        ArrayList<TreeNode> childNodes = new ArrayList<>();
        for (int i = 1; i < data.length; i++) {
            boolean isRight = (i % 2) == 0;
            TreeNode parentNode = parentNodes.get(index);
            // 自己写的构造方法，有问题，即使父节点已经是null了，数据中null的子节点还是要补null，因为这里会一直new
            TreeNode childNode = new TreeNode();
            if (data[i] != null) {
                childNode.val = (int) data[i];
            } else {
                childNode.val = Integer.MAX_VALUE;
            }
            if (!isRight) {
                parentNode.left = childNode;
            } else {
                parentNode.right = childNode;
                index++;
            }
            childNodes.add(childNode);

            if (childNodes.size() == parentNodes.size() * 2) {
                parentNodes = new ArrayList<>(childNodes);
                childNodes.clear();
                index = 0;
            }
        }
    }


    public boolean isValidVal() {
        return -1E9 <= this.val && this.val <= 1E9;
    }

}
